package page.ineffable.phonedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import page.ineffable.phonedemo.model.PhoneSimple;
import page.ineffable.phonedemo.service.PhoneService;
import page.ineffable.phonedemo.service.impl.PhoneServiceImpl;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 测试方法
 *
 * @author lqs2
 * @date 2018/11/10, Sat
 */
public class Test {


    private static PhoneService phoneService;

    private static Logger log = LoggerFactory.getLogger(Test.class);

    private static Pattern p = Pattern.compile("[^0-9]");

    public static void main(String[] args) {
        call();
    }

    /**
     * 测试查询号码
     **/
    private static void call() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String s = scanner.nextLine().trim();
            String s1 = s;
            if ("EXIT".equalsIgnoreCase(s)) {
                break;
            }
            s = getRealParam(s);
            if (s.length() < 7) {
                log.error("{}", "号码格式错误");
                continue;
            }
            log.info("查询的号码是 -> {}", s1);
            long startTime = System.currentTimeMillis();
            if (phoneService == null) {
                phoneService = new PhoneServiceImpl();
            }
            PhoneSimple phone = phoneService.onCall(s);
            if (phone == null) {
                log.error("未知来电");
            } else {
                log.info("查询成功 -> {}", phone);
            }
            long finishTime = System.currentTimeMillis();
            log.info("用时：{} ms", (finishTime - startTime));
        }
    }

    /**
     * 从用户输入的手机号中取出7位前缀
     *
     * @param s 用户输入的手机号
     * @return 前缀
     **/
    private static String getRealParam(String s) {
        Matcher m = p.matcher(s);
        s = m.replaceAll("").trim();
        int startIndex = s.indexOf("1");
        if (startIndex < 0 || s.length() < startIndex + 7) {
            return "";
        }
        s = s.substring(startIndex, startIndex + 7);
        return s;
    }
}
